<?php

namespace app\common\command\task;

use app\common\command\Task;
use app\common\model\Course;
use app\common\model\CoursePaper;
use app\common\model\CourseQuestion;
use Dompdf\Dompdf;
use Dompdf\Options;

/**
 * 生成试卷PDF文档
 */
class GeneratePaperPDF extends Task
{
    /**
     * 执行任务
     * @return void
     */
    public function invoke()
    {
        // 查询多个试卷
        $paperModel = new CoursePaper();
        $where = [
            ['course_id', '=', 603],
            ['tag_id', '=', 40],
            ['id', '=', 64380],
        ];
        $papers = $paperModel->where($where)->select();
        if (!$papers || $papers->isEmpty()) {
            return;
        }

        // 处理多个试卷
        foreach ($papers as $paper) {
            // 查询课程信息
            $courseModel = new Course();
            $course = $courseModel->find($paper->course_id);
            if (!$course) {
                continue; // 跳过没有对应课程的试卷
            }
            $courseName = $course->name;
            $paperName = $courseName . '-' . $paper->name;

            // 查询当前试卷的题目
            $questionModel = new CourseQuestion();
            $questions = $questionModel->where('extend_id', $paper->id)->select();

            if ($questions->isEmpty()) {
                continue; // 跳过没有题目的试卷
            }

            // 构建HTML内容
            $html = '<!DOCTYPE html>';
            $html .= '<html charset="UTF-8">';
            $html .= '<head>';
            $html .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
            $html .= '<style>';
            $html .= 'body { font-family: SimSun, serif; font-size: 14px; line-height: 1.5; }';
            $html .= 'h1 { text-align: center; font-size: 20px; font-weight: bold; }';
            $html .= '.question { margin-bottom: 20px; }';
            $html .= '.question-title { font-weight: bold; font-size: 16px; margin-bottom: 10px; }';
            $html .= '.option { margin-left: 20px; margin-bottom: 5px; }';
            $html .= '.answer { font-weight: bold; color: #FF0000; }';
            $html .= '.explanation { }';
            $html .= '.divider { color: #CCCCCC; margin: 20px 0; }';
            $html .= '</style>';
            $html .= '</head>';
            $html .= '<body>';
            
            // 添加试卷标题
            $html .= '<h1>' . $this->cleanTextForHtml($paperName) . '</h1>';
            
            // 添加题目
            $totalQuestions = count($questions);
            echo "正在处理试卷 {$paperName}，共 {$totalQuestions} 道题" . PHP_EOL;
            
            foreach ($questions as $index => $question) {
                $questionNumber = $index + 1;
                echo "正在处理第 {$questionNumber} 道题，题目ID: {$question->id}" . PHP_EOL;
                
                $html .= '<div class="question">';
                
                // 题目标题
                $questionTitle = $questionNumber . '、' . $question->question_name;
                $questionTitle = $this->cleanTextForHtml($questionTitle);
                $html .= '<div class="question-title">' . $questionTitle . '</div>';
                
                // 解析question_data字段
                if (!empty($question->question_data)) {
                    $questionData = json_decode($question->question_data, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        $questionData = null;
                    }
                    
                    if ($questionData) {
                        // 处理选项
                        if (in_array($question->question_type, [1, 2, 3]) && 
                            isset($questionData['answerOption']) && 
                            is_array($questionData['answerOption']) && 
                            !empty($questionData['answerOption'])) {
                            
                            $options = $questionData['answerOption'];
                            foreach ($options as $key => $option) {
                                if (empty($option) || trim($option) === '') {
                                    continue;
                                }
                                $option = $this->cleanTextForHtml($option);
                                $html .= '<div class="option">' . $key . '. ' . $option . '</div>';
                            }
                        }
                        
                        // 添加正确答案
                        if (isset($questionData['correctOption'])) {
                            $html .= '<div class="answer">正确答案：' . $this->cleanTextForHtml($questionData['correctOption']) . '</div>';
                        }
                        
                        // 添加解析
                        if (isset($questionData['aiExplanation']) && !empty($questionData['aiExplanation'])) {
                            $html .= '<div class="explanation">解析：' . $this->cleanTextForHtml($questionData['aiExplanation']) . '</div>';
                        } elseif (isset($questionData['explanation']) && !empty($questionData['explanation'])) {
                            $html .= '<div class="explanation">解析：' . $this->cleanTextForHtml($questionData['explanation']) . '</div>';
                        }
                    }
                }
                
                $html .= '<div class="divider">─────────────────────────────</div>';
                $html .= '</div>';
            }
            
            $html .= '</body>';
            $html .= '</html>';
            
            // 保存PDF文档
            $filename = $paperName . '_' . date('YmdHis') . '.pdf';
            $filepath = runtime_path() . $filename;
            
            echo "文档统计信息：\n";
            echo "- 总题目数: " . count($questions) . "\n";
            echo "- 文档保存路径: " . $filepath . "\n";
            
            try {
                // 配置Dompdf选项
                $options = new Options();
                $options->set('defaultFont', 'SimSun');
                $options->set('fontDir', runtime_path() . 'fonts/');
                $options->set('fontCache', runtime_path() . 'fonts/');
                $options->set('isRemoteEnabled', true);
                $options->set('isHtml5ParserEnabled', true);
                $options->set('debugPng', false);
                $options->set('debugKeepTemp', false);
                $options->set('debugCss', false);
                $options->set('debugLayout', false);
                $options->set('logOutputFile', '');
                $options->set('tempDir', runtime_path() . 'temp/');
                
                // 创建Dompdf实例
                $dompdf = new Dompdf($options);
                $dompdf->loadHtml($html, 'UTF-8');
                
                // 设置纸张大小和方向
                $dompdf->setPaper('A4', 'portrait');
                
                // 渲染PDF
                $dompdf->render();
                
                // 保存PDF文件
                file_put_contents($filepath, $dompdf->output());
                
                echo "✅ PDF文档成功保存，文件大小: " . filesize($filepath) . " 字节\n";
                
                // 验证文件是否真正保存成功
                if (!file_exists($filepath)) {
                    echo "❌ 警告：文档保存后文件不存在！\n";
                } elseif (filesize($filepath) == 0) {
                    echo "❌ 警告：文档保存后文件大小为0！\n";
                } else {
                    echo "✅ 文档验证通过\n";
                }
            } catch (\Exception $e) {
                echo "❌ 保存PDF文档时出错: " . $e->getMessage() . "\n";
                echo "错误文件: " . $e->getFile() . "\n";
                echo "错误行号: " . $e->getLine() . "\n";
                throw $e;
            } catch (\Error $e) {
                echo "❌ 保存PDF文档时发生致命错误: " . $e->getMessage() . "\n";
                echo "错误文件: " . $e->getFile() . "\n";
                echo "错误行号: " . $e->getLine() . "\n";
                throw $e;
            }

            echo '试卷PDF文档生成完成，文件路径：' . $filepath . PHP_EOL;
        }
    }
    
    /**
     * 清理文本中的特殊字符，确保适合HTML显示
     * 
     * @param string $text 待清理的文本
     * @return string 清理后的文本
     */
    private function cleanTextForHtml($text) {
        // 移除或替换可能导致HTML显示错误的特殊字符
        $text = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text);
        
        // 替换特殊HTML实体
        $text = str_replace(['&nbsp;', '&mdash;', '&ndash;', '&hellip;'], [' ', '—', '–', '…'], $text);
        
        // 确保文本编码为UTF-8
        if (!mb_check_encoding($text, 'UTF-8')) {
            $text = mb_convert_encoding($text, 'UTF-8');
        }
        
        return $text;
    }
}